document.addEventListener('DOMContentLoaded', () => {
  const addGroupButton = document.querySelector('.btn-addGroup');
  const container = document.querySelector('.stu-in');

  // 点击“添加组”按钮时创建新的组
  addGroupButton.addEventListener('click', () => {
    const groupNum = prompt('请输入组号');
    if (groupNum) {
      const groupTitle = `第${groupNum}组`;
      const newGroup = document.createElement('div');
      newGroup.classList.add('group');
      newGroup.innerHTML = `
        <h3>${groupTitle}
          <a class="addStu" href="javascript:void(0)">添加成员</a>
          <a class="delGroup" href="javascript:void(0)">删除本组</a>
        </h3>
        <ul>
          <!-- 在这里添加新成员 -->
        </ul>
      `;
      container.appendChild(newGroup);

      // 绑定新添加组的事件
      bindGroupEvents(newGroup);
    }
  });

  // 初始化绑定现有组的事件
  document.querySelectorAll('.group').forEach(group => bindGroupEvents(group));
});

// 绑定组内按钮的事件
function bindGroupEvents(group) {
  const addStuButton = group.querySelector('.addStu');
  const delGroupButton = group.querySelector('.delGroup');
  const ul = group.querySelector('ul');

  // 点击“添加成员”按钮时增加新成员
  addStuButton.addEventListener('click', () => {
    const studentName = prompt('请输入成员名字');
    if (studentName) {
      const newMember = createMemberElement(studentName);
      ul.appendChild(newMember);
    }
  });

  // 点击“删除本组”按钮时删除整个组
  delGroupButton.addEventListener('click', () => {
    if (confirm('确定要删除这个组吗？')) {
      group.remove();
    }
  });

  // 为现有成员绑定关闭按钮事件
  ul.querySelectorAll('.stu-item').forEach(member => {
    bindMemberEvents(member);
  });
}

// 创建新成员元素并绑定关闭事件
function createMemberElement(name) {
  const newMember = document.createElement('li');
  newMember.classList.add('stu-item');
  newMember.innerHTML = `${name}<div class="close-btn"><span class="iconfont icon-close"></span></div>`;
  bindMemberEvents(newMember);
  return newMember;
}

// 为成员绑定事件
function bindMemberEvents(member) {
  const closeButton = member.querySelector('.close-btn');
  closeButton.addEventListener('click', () => {
    if (confirm(`确定要删除成员 ${member.textContent.trim()} 吗？`)) {
      member.remove();
    }
  });
}
